#include "altpluginviewer.h"

#include "altapplication.h"
#include "altglobals.h"
#include "altmapeditorplugin.h"
#include "altmapplugin.h"

#include <QLabel>
#include <QPushButton>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QVBoxLayout>

#define ALT_CREATE_ITEM(parentItem) { QTreeWidgetItem* item = new QTreeWidgetItem(parentItem, QStringList() << plugin->pluginName() << plugin->filePath()); \
               item->setData(0, Qt::UserRole, plugin->pluginDescription()); }

namespace Alt {
     //public
     PluginViewer::PluginViewer(QWidget* parent) : QDialog(parent) {
          init();
     }

     //public slots
     void PluginViewer::showPluginInfo(){
          QTreeWidgetItem* item = m_pluginTree->currentItem();
          m_pluginInfo->setText(item->data(0, Qt::UserRole).toString());
          return;
     }

     //private
     void PluginViewer::init(){
          setWindowTitle(tr("Alt plugins"));

          QVBoxLayout* layout = new QVBoxLayout(this);

          m_pluginTree = new QTreeWidget(this);
          connect(m_pluginTree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(showPluginInfo()));
          m_pluginTree->setColumnCount(2);
          m_pluginTree->setHeaderLabels(QStringList() << tr("Plugin") << tr("Path"));

          QTreeWidgetItem* pluginsItem = new QTreeWidgetItem(m_pluginTree, QStringList() << tr("All plugins") << "");
          QTreeWidgetItem* mapPluginsItem = new QTreeWidgetItem(pluginsItem, QStringList() << tr("Map plugins") << "");
          QTreeWidgetItem* mapEditorPluginsItem = new QTreeWidgetItem(pluginsItem, QStringList() << tr("Map editor plugins") << "");
          QTreeWidgetItem* otherPluginsItem = new QTreeWidgetItem(pluginsItem, QStringList() << tr("Other plugins") << "");

          foreach(QObject* obj, Application::pluginObjects()){
               Plugin* plugin = qobject_cast<Plugin*>(obj);
               MapPlugin* mapPlugin = qobject_cast<MapPlugin*>(obj);
               MapEditorPlugin* mapEditorPlugin = qobject_cast<MapEditorPlugin*>(obj);
               bool isOther = true;
               if(mapPlugin){
                    ALT_CREATE_ITEM(mapPluginsItem);
                    isOther = false;
               }
               if(mapEditorPlugin){
                    ALT_CREATE_ITEM(mapEditorPluginsItem);
                    isOther = false;
               }
               if(isOther){
                    ALT_CREATE_ITEM(otherPluginsItem);
               }
          }

          m_pluginInfo = new QLabel(this);

          QPushButton* okButton = new QPushButton(tr("Ok"), this);
          connect(okButton, SIGNAL(released()), this, SLOT(accept()));

          layout->addWidget(m_pluginTree);
          layout->addWidget(m_pluginInfo);
          layout->addWidget(okButton);
          return;
     }
}
